package com.iflyings.android.util

import android.Manifest.permission
import android.annotation.SuppressLint
import android.content.Context
import android.os.IBinder
import android.os.PowerManager
import androidx.annotation.RequiresPermission
import java.io.FileOutputStream

object SystemUtils {

    @SuppressLint("PrivateApi")
    fun getProperty(key: String, defaultValue: String = ""): String {
        val method = Class.forName("android.os.SystemProperties")
            .getDeclaredMethod("get", String::class.java, String::class.java)
        return method.invoke(null, key, defaultValue) as String
    }

    @SuppressLint("DiscouragedPrivateApi", "PrivateApi")
    fun setProperty(key: String, value: String) {
        val method = Class.forName("android.os.SystemProperties")
            .getDeclaredMethod("set", String::class.java, String::class.java)
        method.invoke(null, key, value)
    }

    @SuppressLint("DiscouragedPrivateApi", "PrivateApi")
    fun addService(name: String, service: IBinder) {
        val method = Class.forName("android.os.ServiceManager")
            .getDeclaredMethod("addService", String::class.java, IBinder::class.java)
        method.invoke(null, name, service)
    }

    @SuppressLint("DiscouragedPrivateApi", "PrivateApi")
    fun getService(name: String): IBinder? {
        val method = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String::class.java)
        return method.invoke(null, name) as IBinder?
    }

    @RequiresPermission(permission.REBOOT)
    fun reboot(context: Context, reason: String) {
        val powerManager = context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
        powerManager.reboot(reason)
    }

    fun captureScreenShot(localPath: String) {
        var process: Process? = null
        try {
            val deviceName = getProperty("ro.mooncell.model", "unknown")
            process = if (deviceName.contains("rk3128")) {
                Runtime.getRuntime().exec("screencap -j")
            } else {
                Runtime.getRuntime().exec("screencap -p")
            }
            process.inputStream.use { inStream ->
                FileOutputStream(localPath).use { outStream ->
                    val buffer = ByteArray(10 * 1024)
                    var len = 0
                    while (inStream.read(buffer).apply { len = this } > 0) {
                        outStream.write(buffer, 0, len)
                    }
                }
            }
        } finally {
            process?.destroy()
        }
    }
}